<template>
    <div class="parent">
        <div id="container"></div>
        <div id="controls"></div>
    </div>
</template>

<script setup lang="ts"> 
import { onMounted } from 'vue';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js';

onMounted(()=>{
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.set(0,10,20);

    const renderer = new THREE.WebGLRenderer({antialias: true});
    renderer.setSize(window.innerWidth, window.innerHeight);
    //开启阴影
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    document.querySelector('#container')?.appendChild(renderer.domElement);

    const controls = new OrbitControls(camera, renderer.domElement);

    const light = new THREE.DirectionalLight(0xffffff, 1);
    light.position.set(0,20,10);
    //开启阴影
    light.castShadow = true;
    scene.add(light);
    scene.add(light.target);
    
    const loader = new THREE.TextureLoader();
    const texture = loader.load('/pngs/checker.png');
    texture.wrapS = THREE.RepeatWrapping;
    texture.wrapT = THREE.RepeatWrapping;
    texture.magFilter = THREE.NearestFilter;
    texture.colorSpace = THREE.SRGBColorSpace;
    texture.repeat.set(20,20);
    const planeMaterial = new THREE.MeshPhongMaterial({
        map:texture,
        side:THREE.DoubleSide
    });
    const plane = new THREE.Mesh(
        new THREE.PlaneGeometry(40,40),
        planeMaterial
    );
    plane.rotation.x = Math.PI * -.5;
    plane.castShadow = true;
    plane.receiveShadow = true;
    scene.add(plane);


    const box1 = new THREE.Mesh(
        new THREE.BoxGeometry(4,4,4),
        new THREE.MeshPhongMaterial({color:'red'})
    );

    box1.position.set(0,2,0);
    box1.castShadow = true;
    box1.receiveShadow = true;
    scene.add(box1);

    const box2 = new THREE.Mesh(
        new THREE.BoxGeometry(4,4,4),
        new THREE.MeshPhongMaterial({color:'blue'})
    );

    box2.position.set(0,8,5);
    box2.castShadow = true;
    box2.receiveShadow = true;
    scene.add(box2);

    const gui = new GUI({container: document.getElementById('controls')!!});
    gui.add(light.position,"x",-10,10,1).name("横坐标");
    gui.add(light.position,"y",0,40,1).name("纵坐标");
    gui.add(light.position,"z",0,20,1).name("z坐标");

    const render = function () {
        requestAnimationFrame(render);
        renderer.render(scene, camera);
    };

    requestAnimationFrame(render);

});
</script>

<style scoped>
.parent {
    position: relative;
    width: 100%;
    height: 100%;
}
.parent > * {
    position: absolute;
}
#controls{
    right: 0;
}
</style>